#!/usr/bin/env bash

: ${__baidu_wiki_format:=text}
__baidu_wiki_url=https://baike.baidu.com/item

# 以固定模板输出 html
__print_html(){
  cat <<EOF
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>$__TITLE</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .title {
            color: #2c3e50;
            border-bottom: 3px solid #3498db;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
        .content {
            font-size: 16px;
            line-height: 1.8;
            color: #555;
            white-space: pre-line;
        }
        .keywords-section {
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px solid #eee;
        }
        .keywords-title {
            color: #e74c3c;
            font-size: 20px;
            margin-bottom: 15px;
        }
        .keyword-item {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 10px;
            transition: transform 0.2s, box-shadow 0.2s;
            text-decoration: none;
            display: block;
            color: inherit;
        }
        .keyword-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            background: #e8f4f8;
        }
        .keyword-title {
            font-weight: bold;
            color: #2980b9;
            font-size: 18px;
            margin-bottom: 5px;
        }
        .keyword-id {
            color: #7f8c8d;
            font-size: 12px;
            margin-bottom: 5px;
        }
        .keyword-class {
            display: inline-block;
            background: #3498db;
            color: white;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 12px;
            margin-bottom: 8px;
        }
        .keyword-desc {
            color: #666;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="title">$__TITLE</h1>
        <div class="content">$__CONTENT</div>
EOF

      # 根据 __has_keyword 决定是否显示候选词条
      if $__has_keyword;then
        cat <<EOF
        
        <div class="keywords-section">
            <h2 class="keywords-title">相关词条候选</h2>
EOF
        
        # 生成带链接的关联词条HTML
        jq -r '.[] | 
          "<a href=\"'$__baidu_wiki_url'" + (.title | @uri) + "/" + (.id | tostring) + "\" class=\"keyword-item\" target=\"_blank\">" +
          "<div class=\"keyword-title\">" + .title + "</div>" +
          "<div class=\"keyword-id\">词条ID: " + (.id | tostring) + "</div>" +
          "<span class=\"keyword-class\">" + .class + "</span>" +
          "<div class=\"keyword-desc\">" + .desc + "</div>" +
          "</a>"
        ' <<<"$__KEYWORD"
        
        cat <<EOF
        </div>
EOF
      fi

      cat <<EOF
    </div>
</body>
</html>
EOF
}

# 以固定模板输出 text
__print_text(){
  cat <<<"$__TITLE_CONTENT"
  if $__has_keyword;then
    echo -e "\n### 相关词条"
    jq -r '.[] | 
    "## 名称: \(.title), ItemId: \(.id)\n" +
    " - 分类: \(.class)\n" +
    " - 描述: \(.desc)\n" +
    "-----------------\n"
    ' <<<"$__KEYWORD"
  fi
}

# 以固定模板输出 json
__print_json(){
  jq \
    --raw-input --slurp \
    'split("\n") | {title: .[0], content: .[1]}' <<<"$__TITLE_CONTENT" |
    (
      if $__has_keyword;then
        jq --argjson keywords "$__KEYWORD" '.keywords = $keywords'
      else
        jq
      fi
    )
}

# 以固定模板输出 xml
__print_xml(){
  cat <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<baidu_wiki>
  <title>$(echo "$__TITLE" | sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g; s/"/\&quot;/g; s/'"'"'/\&apos;/g')</title>
  <content>$(echo "$__CONTENT" | sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g; s/"/\&quot;/g; s/'"'"'/\&apos;/g')</content>
EOF

  if $__has_keyword; then
    echo "  <keywords>"
    jq -r ".[] | 
    \"    <keyword>\" +
    \"\n      <id>\" + (.id | tostring) + \"</id>\" +
    \"\n      <class>\" + (.class | gsub(\"&\"; \"&amp;\") | gsub(\"<\"; \"&lt;\") | gsub(\">\"; \"&gt;\") | gsub(\"\\\"\"; \"&quot;\") | gsub(\"'\"; \"&apos;\")) + \"</class>\" +
    \"\n      <description>\" + (.desc | gsub(\"&\"; \"&amp;\") | gsub(\"<\"; \"&lt;\") | gsub(\">\"; \"&gt;\") | gsub(\"\\\"\"; \"&quot;\") | gsub(\"'\"; \"&apos;\")) + \"</description>\" +
    \"\n    </keyword>\"
    " <<<"$__KEYWORD"
    echo "  </keywords>"
  fi

  cat <<EOF
</baidu_wiki>
EOF
}

# 主要逻辑处理
__Main__(){
  # 从百度百科获取数据 in HTML
  __DATA="$(
    curl -sL --connect-timeout 3 "$__baidu_wiki_url/$1" ||
    echo '<title>Error</title><div class="lemmaSummary_ERROR DEMO">Error Message Demo</div>'
  )"

  # 检查数据是否包含错误信息
  [[ "$__DATA" == *"lemmaSummary_ERROR DEMO"* ]] && exec echo "请求发生错误，请检查网络"

  # 提取基本内容 in title and content, ASCII Text
  __TITLE_CONTENT="$(
    grep -oP '<title>.*?</title>|<div class="lemmaSummary_[^"]*">.*?</div>' <<<"$__DATA" |
    sed -E 's/<[^>]*>//g;s/&quot;/"/g;s/&nbsp;/ /g;s/&lt;/</g;s/&gt/>/g' |
    sed -E 's/&#x([0-9A-Fa-f]{2,4});/\\x\1/g' | printf "%b\n" "`cat`"
  )"

  # 提取标题 in title, ASSCII Text
  __TITLE="$(sed -n '1p' <<<"$__TITLE_CONTENT")"

  # 提取内容 in content, ASSCII Text
  __CONTENT="$(sed -n '2,$p' <<<"$__TITLE_CONTENT")"

  # 提取多义词候选 in JSON
  __KEYWORD_JSON="$(
    grep -Po "<script>window.PAGE_DATA=.*?</script>" <<<"$__DATA" |
    sed "s/<script>window.PAGE_DATA= //g;s/<\/script>//g"
  )"

  # 判断是否包含多义词候选
  if jq -e '.navigation.lemmas? // [] | length > 0' <<<"$__KEYWORD_JSON" &>/dev/null;then
    __has_keyword=true
    __KEYWORD="$(
      jq '[.navigation.lemmas[] | {id: .lemmaId, title: .lemmaTitle, desc: .lemmaDesc, class: .classify[0]}]' <<<"$__KEYWORD_JSON"
    )"
  else
    __has_keyword=false
  fi

  # 格式化输出
  __print_$__baidu_wiki_format
}

[ -z "$1" ] && exec echo -e "用法: `basename $BASH_SOURCE` <关键词/词条ID?> --<json|text|html|xml>\n\n  例: `basename $BASH_SOURCE` \"命令行界面/9910197\" --json\n\n数据来源：百度百科（`dirname $__baidu_wiki_url`）\n"

if ! [[ "$1" =~ ^[a-zA-Z0-9\u4e00-\u9fa5]+(/[0-9]+)?$ ]]; then
  exec echo -e "错误: 关键词格式无效\n\n支持的格式:\n  - 纯关键词: CLI\n  - 关键词+词条ID: 命令行界面/9910197\n\n请检查输入格式"
fi

if [[ "$2" && "$2" =~ --(json|text|html|xml) ]];then
  __baidu_wiki_format="${BASH_REMATCH[1]}"
fi
__Main__ "$1"